package com.xiaomaoguai.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.CreateMode;

/**
 * @author :WeiHui.Zhang
 * @fileName: CreateNodeTest.java
 * @date : 2016年11月4日 下午1:48:31
 * @version:V1.00
 */
public class CreateNodeTest {

	private static final String zkClusterAddress = "127.0.0.1:2181";
	private static final int sessionTimeoutMs = 5000;
	private static final int connectionTimeoutMs = 3000;

	public static void main(String[] args) {
		CuratorFramework client = null;
		try {
			// 重试策略
			RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

			client = CuratorFrameworkFactory.builder()//
					.connectString(zkClusterAddress)//
					.sessionTimeoutMs(sessionTimeoutMs)//
					.connectionTimeoutMs(connectionTimeoutMs)//
					.retryPolicy(retryPolicy)//
					// .namespace(properties.getProjectName())// 增加命名空间
					.build();

			client.getConnectionStateListenable().addListener((client1, newState) -> {
				System.out.println("client state:" + newState.name());
				switch (newState) {
					case CONNECTED:

						break;
					case RECONNECTED:

						break;
					case SUSPENDED:

						break;
					case LOST:

						break;
					case READ_ONLY:

						break;
					default:
						break;
				}

			});
			client.start();
			client.create().forPath("/path", "hello world".getBytes("UTF-8"));
			// 构造临时节点
			client.create().withMode(CreateMode.EPHEMERAL).forPath("/path/APP1", "hello world".getBytes("UTF-8"));
			System.out.println("成功");

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			CloseableUtils.closeQuietly(client);
		}
	}
}
